<?php
/**
 * Hello Model for Hello World Component
 *
 * @package    Joomla.Tutorials
 * @subpackage Components
 * @link http://dev.joomla.org/component/option,com_jd-wiki/Itemid,31/id,tutorials:modules/
 * @license		GNU/GPL
 */

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();

jimport( 'joomla.application.component.model' );
//jimport( 'joomla.application.component.helper' );

/**
 * Hello Model
 *
 * @package    Joomla.Tutorials
 * @subpackage Components
 */
class JBSModelAssets extends JModel
{
	/**
	 * EventTypes data array
	 *
	 * @var array
	 */
	public $_data = null;

	/**
	 * Events total
	 *
	 * @var integer
	 */
	public $_total = null;

	/**
	 * Pagination object
	 *
	 * @var object
	 */
	public $_pagination = null;

	function __construct()
	{
		parent::__construct();

		global $mainframe, $option;

		$limit		= $mainframe->getUserStateFromRequest( $option.'limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
		$limitstart = $mainframe->getUserStateFromRequest( $option.'limitstart', 'limitstart', 0, 'int' );

		$this->setState('limit', $limit);
		$this->setState('limitstart', $limitstart);

		$array = JRequest::getVar('cid',  0, '', 'array');
		$this->setId((int)$array[0]);
	}

	/**
	 * Method to get assets item data
	 *
	 * @access public
	 * @return array
	 */
	function getDataList()
	{
		// Lets load the content if it doesn't already exist
		if (empty($this->_data))
		{
			$query = $this->_buildQuery();
			//echo $query;
			$this->_data = $this->_getList($query, $this->getState('limitstart'), $this->getState('limit'));
		}
		//print_r($this->_data);

		return $this->_data;
	}

	/**
	 * Total nr of eventtypes
	 *
	 * @access public
	 * @return integer
	 */
	function getTotal()
	{
		// Lets load the total nr if it doesn't already exist
		if (empty($this->_total))
		{
			$query = $this->_buildQuery();
			$this->_total = $this->_getListCount($query);
		}

		return $this->_total;
	}

	/**
	 * Method to get a pagination object for the groups
	 *
	 * @access public
	 * @return integer
	 */
	function getPagination()
	{
		// Lets load the content if it doesn't already exist
		if (empty($this->_pagination))
		{
			jimport('joomla.html.pagination');
			$this->_pagination = new JPagination( $this->getTotal(), $this->getState('limitstart'), $this->getState('limit') );
		}

		return $this->_pagination;
	}

		/**
	 * Build the query
	 *
	 * @access private
	 * @return string
	 */
	function _buildQuery()
	{
		// Get the WHERE and ORDER BY clauses for the query
		$where		= $this->_buildContentWhere();
		$orderby	= $this->_buildContentOrderBy();
		$query = 'SELECT '.
				'	a.id, '.
				'	a.assetgroup_id, '.
				'	a.name, '.
				'	a.description, '.
				'	a.img, '.
				'	a.code, '.
				'	a.color, '.
				'	ag.name AS assetgroups_name '.
				'FROM #__jbschedule_assets a ' .
				' Inner Join #__jbschedule_assetgroups ag '.
				' ON ag.id = a.assetgroup_id'
				. $where
				. $orderby;
//		echo $query;
		return $query;
	}

	/**
	 * Build the order clause
	 *
	 * @access private
	 * @return string
	 */
	function _buildContentOrderBy()
	{
		global $mainframe, $option;
		$nameField  = 'a.name';

		$filter_order		= $mainframe->getUserStateFromRequest( $option.'.assets.filter_order', 'filter_order',$nameField, 'cmd' );
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( $option.'.assets.filter_order_Dir', 'filter_order_Dir', '', 'word' );

		$orderby 	= ' ORDER BY '.$filter_order.' '.$filter_order_Dir.', '.$nameField;

		return $orderby;
	}

	/**
	 * Build the where clause
	 *
	 * @access private
	 * @return string
	 */
	function _buildContentWhere()
	{
		global $mainframe, $option;

		$search 			= $mainframe->getUserStateFromRequest( $option.'.search', 'search', '', 'string' );
		$search 			= $this->_db->getEscaped( trim(JString::strtolower( $search ) ) );

		$where = array();
		// a.name là filed trong db
		$where[] = ' LOWER(a.name) LIKE \'%'.$search.'%\' ';

		$where 		= ( count( $where ) ? ' WHERE ' . implode( ' AND ', $where ) : '' );

		return $where;
	}

	/**
	 * Method to set the hello identifier
	 *
	 * @access	public
	 * @param	int Hello identifier
	 * @return	void
	 */
	function setId($id)
	{
		// Set id and wipe data
		$this->_id		= $id;
		$this->_data	= null;
	}
	/*
	function &getAllData()
	{
		if (empty( $this->_data ))
		{
			$query = 'SELECT '.
				'#__jbschedule_assets.id, '.
				'#__jbschedule_assets.assetgroup_id, '.
				'#__jbschedule_assets.name, '.
				'#__jbschedule_assets.description, '.
				'#__jbschedule_assets.img, '.
				'#__jbschedule_assetgroups.name AS assetgroups_name '.
				'FROM #__jbschedule_assets ' .
				'Inner Join #__jbschedule_assetgroups '.
				'ON #__jbschedule_assetgroups.id = #__jbschedule_assets.assetgroup_id';
			$this->_data = $this->_getList( $query );
		}

		return $this->_data;
	}
	*/
	/**
	 * Method to get a hello
	 * @return object with data
	 */
	function &getData()
	{
		// Load the data
		if (empty( $this->_data )) {
			$query = ' SELECT * FROM #__jbschedule_assets '.
					'  WHERE id = '.$this->_id;
			$this->_db->setQuery( $query );
			$this->_data = $this->_db->loadObject();
		}
		if (!$this->_data) {
			$this->_data = new stdClass();
			$this->_data->id = 0;
			$this->_data->name = null;
			$this->_data->description = null;
		}
		return $this->_data;
	}

	/**
	 * Method to get a asset by Name
	 * @return object with data
	 */
	function &findByName($name){
		$query = "SELECT * FROM #__jbschedule_assets ".
				"WHERE name = '".$name."'";
		$this->_db->setQuery( $query );
		$data = $this->_db->loadObject();	//Lay ve Object
		if(!$data)
			return null;	//Khong tim thay

		//Tim thay
		$table =& $this->getTable(); //Tao moi 1 Asset Table
		$table->bind($data);	//Bind du lieu tu $data vao $table
		return $table;
	}

	/**
	 * Method to store a record
	 *
	 * @access	public
	 * @return	boolean	True on success
	 */
	function store()
	{
		// BEGIN: Server Side Validation
		$jAp=& JFactory::getApplication();
		if ($_POST['check']!=JUtility::getToken()) {
			if ($_POST['check']=='post')
				$jAp->enqueueMessage('Please check all the fields of the form.','error');
			return false;
		}
		// END: Server Side Validation

		$row =& $this->getTable();

		$data = JRequest::get( 'post' );

		// Bind the form fields to the hello table
		if (!$row->bind($data)) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		// Make sure the record is valid
		if (!$row->check()) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		//Check if Add new function and the asset name is already exists
		$assetgroup = $this->findByName($row->name);
		if( $assetgroup != null && $assetgroup->id != $row->id){
	   		$jAp->enqueueMessage('The name "'.$row->name.'" is already exists. Try again please.','error');
	   		return false;
	   }

		// Store the web link table to the database
		if (!$row->store()) {
			$this->setError( $row->getErrorMsg() );
			return false;
		}

		return true;
	}

	/**
	 * Method to delete record(s)
	 *
	 * @access	public
	 * @return	boolean	True on success
	 */
	function delete()
	{
		$cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );

		$row =& $this->getTable();

		if (count( $cids ))
		{
			foreach($cids as $cid) {
				if (!$row->delete( $cid )) {
					$this->setError( $row->getErrorMsg() );
					return false;
				}
			}
		}
		return true;
	}
}
